<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
    >
      <el-form-item label="清洗计划名称" prop="cplanName">
        <el-input v-model="formData.cplanName" placeholder="请输入餐具清洗计划名称" />
      </el-form-item>
      <el-form-item v-if="formType === 'update'" label="清洗计划编号" prop="cplanCode">
        <el-input v-model="formData.cplanCode" placeholder="请输入餐具清洗计划编号" />
      </el-form-item>
      <el-form-item label="关联航班号" prop="flightNo">
        <el-input v-model="formData.flightNo" placeholder="请输入关联航班号" />
      </el-form-item>
      <el-form-item label="餐具" prop="tablewareType">
        <el-select
          v-model="formData.tablewareId"
          placeholder="请选择餐具"
          class="w-1/1"
          filterable
          :filter-method="getSimpleList"
        >
          <el-option
            v-for="simple in SimpleList"
            :key="simple.id"
            :label="simple.name"
            :value="simple.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="餐具数量(个)" prop="tablewareQty">
        <el-input-number
          v-model="formData.tablewareQty"
          :min="0"
          controls-position="right"
          placeholder="请输入餐具数量(个)"
        />
      </el-form-item>
      <el-form-item label="清洗状态" prop="cleaningStatus">
        <el-select v-model="formData.cleaningStatus" placeholder="请选择清洗状态" class="w-1/1">
          <el-option
            v-for="item in getStrDictOptions(DICT_TYPE.ACM_CLEANING_STATUS)"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="特别说明" prop="specialRemarks">
        <el-input
          type="textarea"
          :rows="4"
          maxlength="400"
          show-word-limit
          v-model="formData.specialRemarks"
          placeholder="请输入特别说明"
        />
      </el-form-item>
      <el-form-item label="计划有效期" prop="expireDate">
        <el-date-picker
          v-model="formData.expireDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { TwCleaningPlanApi, TwCleaningPlanVO } from '@/api/pplan/twcleaningplan'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { TablewareApi, TablewareVO } from '@/api/pplan/tableware' // 导入TablewareVO类型

/** 生产计划-餐具清洗计划 表单 */
defineOptions({ name: 'TwCleaningPlanForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

// 弹窗基础状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('') // create/update

// 表单数据
const formData = ref({
  id: undefined,
  cplanName: undefined,
  cplanCode: undefined,
  flightNo: undefined,
  tablewareId: undefined,
  tablewareQty: undefined,
  cleaningStatus: undefined,
  specialRemarks: undefined,
  startDate: undefined,
  endDate: undefined,
  remarks: undefined,
  expireDate: []
})

// 表单校验规则
const formRules = reactive({
  cplanName: [{ required: true, message: '餐具清洗计划名称不能为空', trigger: 'blur' }],
  flightNo: [{ required: true, message: '关联航班号不能为空', trigger: 'blur' }],
  tablewareId: [{ required: true, message: '餐具不能为空', trigger: 'change' }],
  tablewareQty: [{ required: true, message: '餐具数量(个)不能为空', trigger: 'blur' }],
  cleaningStatus: [{ required: true, message: '清洗状态不能为空', trigger: 'change' }],
  startDate: [{ required: false, message: '计划有效期开始不能为空', trigger: 'blur' }],
  endDate: [{ required: false, message: '计划有效期结束不能为空', trigger: 'blur' }]
})

const formRef = ref() // 表单Ref

// -------------------------- 核心修改：解决餐具回显问题 --------------------------
// 1. 新增：存储完整的餐具列表（仅加载一次，避免重复请求）
const tablewareAllList = ref<TablewareVO[]>([])

// 2. 新增：加载完整餐具列表的方法
const loadAllTablewares = async () => {
  // 已加载过则直接返回，避免重复请求接口
  if (tablewareAllList.value.length > 0) return tablewareAllList.value
  const data = await TablewareApi.getTablewareSimpleList('')
  tablewareAllList.value = data // 缓存完整餐具列表
  return data
}

// 3. 修改：餐具列表过滤方法（确保已选餐具在下拉列表中）
const SimpleList = ref<TablewareVO[]>([]) // 用于下拉显示的餐具列表
const getSimpleList = async (query?: string) => {
  // 确保先加载完整餐具列表
  await loadAllTablewares()

  // 步骤1：提取表单中已选的餐具ID（单条选择，直接取tablewareId）
  const selectedTablewareId = formData.value.tablewareId
  const selectedTablewares: TablewareVO[] = []
  // 若有已选ID，从完整列表中找到对应的餐具
  if (selectedTablewareId) {
    const selected = tablewareAllList.value.find((item) => item.id === selectedTablewareId)
    if (selected) selectedTablewares.push(selected)
  }

  // 步骤2：根据查询条件过滤显示列表（兼顾性能，无查询时只显示前200条）
  let filteredTablewares: TablewareVO[] = []
  if (!query) {
    // 无查询时：取完整列表前200条
    filteredTablewares = [...tablewareAllList.value].slice(0, 200)
  } else {
    // 有查询时：按餐具名称模糊匹配
    filteredTablewares = tablewareAllList.value.filter((item) =>
      item.name.toLowerCase().includes(query.toLowerCase())
    )
  }

  // 步骤3：合并“已选餐具”和“过滤结果”，并通过Map去重（避免重复选项）
  SimpleList.value = Array.from(
    new Map([...selectedTablewares, ...filteredTablewares].map((item) => [item.id, item])).values()
  )
  return SimpleList.value
}
// ------------------------------------------------------------------------------

/** 打开弹窗（修改：加载完整餐具列表并补全回显数据） */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  // 先加载完整餐具列表，再初始化显示列表
  await loadAllTablewares()
  await getSimpleList('')

  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 修改时加载清洗计划数据，并确保已选餐具在下拉列表中
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TwCleaningPlanApi.getTwCleaningPlan(id)
      formData.value.expireDate = [formData.value.startDate, formData.value.endDate]
      // 重新触发过滤，补全已选餐具
      await getSimpleList('')
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 暴露open方法供外部调用

/** 提交表单（原有逻辑未修改） */
const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = formData.value as unknown as TwCleaningPlanVO
    if (formType.value === 'create') {
      await TwCleaningPlanApi.createTwCleaningPlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await TwCleaningPlanApi.updateTwCleaningPlan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单（原有逻辑未修改） */
const resetForm = () => {
  formData.value = {
    id: undefined,
    cplanName: undefined,
    cplanCode: undefined,
    flightNo: undefined,
    tablewareId: undefined,
    tablewareQty: undefined,
    cleaningStatus: undefined,
    specialRemarks: undefined,
    startDate: undefined,
    endDate: undefined,
    remarks: undefined
  }
  formRef.value?.resetFields()
}
</script>